﻿<?php
	class WebApp
	{
		static private $_application = NULL;
		static private $_app = NULL;
		protected $registry;
		protected $db;
		protected $router;
		protected $config;
		
		public static function __autoloadMVC($class_name)
		{
			$filename = strtolower($class_name) . '.php';
			if($class_name == "")
			$filename = strtolower($class_name) . '.php';
			$file = site_path . 'classes' . DIRSEP . $filename;
	
			if (file_exists($file) == false) {
	
					return false;
			}
	
			include ($file);
		}
		private function __construct($cfg)
		{
			//
			$count_sim = strrpos($_SERVER['REQUEST_URI'], DIRSEP);
			$str = substr($_SERVER['REQUEST_URI'], 0, $count_sim + 1);
			define("BASE_URL", $_SERVER['HTTP_HOST'].$str);
			//
			WebApp::setApp($this);
			$this->config = require($cfg);
			spl_autoload_register("WebApp::__autoloadMVC");
			$this->registry = new Registry;

			$this->registry->set('config', $cfg);
			$this->build();
			
			$this->router = new Router($this->registry);
			
			$this->registry->set ('router', $this->router);
			
			$this->router->setPath (site_path . 'controllers');
		}
		
		public static function app()
		{
			/*if (self::$_app == NULL)
			{
			  	self::$_app = new WebApp($cfg);
			}*/
			return self::$_app;
		}
		public static function setApp($app)
		{
			/*if (self::$_app == NULL)
			{
			  	self::$_app = new WebApp($cfg);
			}*/
			//return self::$_app;
			self::$_app = $app;
		}
		
		public static function createWebApp($cfg)
		{
			if (self::$_application == NULL)
			{
			  	self::$_application = new WebApp($cfg);
			}
			return self::$_application;
		}
		
		public function run()
		{
			$this->router->delegate();
		}
		
		protected function build()
		{
			$this->registry->set('theme', $this->config['theme']);
		}
		
		public function getThemePath()
		{
			
			return 'http://'.BASE_URL.'themes'.'/'.$this->registry->get('theme').'/';
		}
	}